import { useState, useEffect, lazy, Suspense } from 'react'
import { ToastContainer } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'
import ImageUploader from './components/ImageUploader'
import Header from './components/Header'
import Sidebar from './components/Sidebar'
import FooterPro from './components/FooterPro'
import ProgressSteps from './components/ProgressSteps'
import HelpButton from './components/HelpButton'
import { useStore } from './store/useStore'
import { ModelViewerSkeleton, OrderListSkeleton } from './components/Skeleton'
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts'

// 懒加载非关键组件
const ModelViewer = lazy(() => import('./components/ModelViewer'))
const OrderList = lazy(() => import('./components/OrderList'))
const AddressManager = lazy(() => import('./components/AddressManager'))

function App() {
  const { currentStep } = useStore()
  const [showOrderList, setShowOrderList] = useState(false)
  const [showAddressManager, setShowAddressManager] = useState(false)
  const [sidebarCollapsed, setSidebarCollapsed] = useState(() => {
    return localStorage.getItem('sidebarCollapsed') === 'true'
  })
  
  // 保存侧边栏状态到localStorage
  useEffect(() => {
    localStorage.setItem('sidebarCollapsed', sidebarCollapsed)
  }, [sidebarCollapsed])
  
  const toggleSidebar = () => {
    setSidebarCollapsed(!sidebarCollapsed)
  }

  // 键盘快捷键
  useKeyboardShortcuts({
    'escape': () => {
      setShowOrderList(false)
      setShowAddressManager(false)
    },
    'ctrl+o': () => setShowOrderList(true),
  })

  return (
    <div className="min-h-screen flex flex-col" style={{ background: 'linear-gradient(135deg, rgb(23, 23, 23) 0%, rgba(30, 30, 30, 0.95) 100%)' }}>
      {/* Header */}
      <Header 
        onOpenOrders={() => setShowOrderList(true)}
        onOpenAddress={() => setShowAddressManager(true)}
        onToggleSidebar={toggleSidebar}
      />
      
      {/* 主布局：侧边栏 + 内容 */}
      <div className="flex flex-1 pt-[72px]">
        {/* 侧边栏 */}
        <Sidebar 
          isCollapsed={sidebarCollapsed} 
          onToggle={toggleSidebar}
          onOpenOrders={() => setShowOrderList(true)}
          onOpenAddress={() => setShowAddressManager(true)}
        />
        
        {/* 主内容区域 */}
        <div className="flex-1 flex flex-col relative overflow-hidden">
          {/* 科技感网格背景 */}
          <div className="absolute inset-0 opacity-30 pointer-events-none" style={{
            backgroundImage: `
              linear-gradient(45deg, transparent 49%, rgba(56, 139, 253, 0.1) 50%, transparent 51%),
              linear-gradient(-45deg, transparent 49%, rgba(56, 139, 253, 0.1) 50%, transparent 51%)
            `,
            backgroundSize: '20px 20px'
          }}></div>
          
          {/* 径向渐变光效 */}
          <div className="absolute top-0 left-1/4 w-[600px] h-[600px] opacity-10" style={{
            background: 'radial-gradient(circle, rgba(56, 139, 253, 0.3) 0%, transparent 70%)',
            filter: 'blur(60px)'
          }}></div>
      
          <main className="flex-1 px-4 sm:px-6 py-4 sm:py-6 relative z-10 overflow-y-auto">
            {/* 面包屑导航 - 仅桌面端显示 */}
            <div className="hidden lg:flex items-center gap-2 text-sm mb-4 text-gray-400">
              <a href="#" className="hover:text-blue-400 transition-colors flex items-center gap-1 px-2 py-1 rounded hover:bg-white/5">
                <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                </svg>
                <span>首页</span>
              </a>
              <span>/</span>
              <span className="text-white font-medium">3D定制工坊</span>
            </div>
            
            {/* 进度流程可视化 */}
            <div className="mb-6 sm:mb-8">
              <ProgressSteps />
            </div>

            {/* 主要内容区域 - 两列布局 */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-4 sm:gap-6 mb-6 lg:items-stretch">
              {/* 左列：上传和生成面板 - 4列 */}
              <div className="lg:col-span-4 animate-slide-up flex">
                <ImageUploader />
              </div>

              {/* 右列：3D预览 - 8列 */}
              <div className="lg:col-span-8 animate-slide-up flex" style={{ animationDelay: '0.1s' }}>
                <Suspense fallback={<ModelViewerSkeleton />}>
                  <ModelViewer />
                </Suspense>
              </div>
            </div>

            {/* 数据持久化提示（仅在有订单时显示）*/}
            {useStore.getState().orders?.length > 0 && (
              <div className="mt-6 glass-effect-dark rounded-xl p-4 border border-green-500/30 animate-scale-in">
                <p className="text-sm text-gray-300 flex items-center justify-center space-x-2">
                  <svg className="w-5 h-5 text-green-400 animate-pulse" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                  </svg>
                  <span>
                    <strong className="text-green-400">💾 数据已保存：</strong>
                    您的 {useStore.getState().orders.length} 个订单已自动保存到浏览器，刷新页面不会丢失
                  </span>
                </p>
              </div>
            )}
          </main>
        </div>
      </div>

      {/* 页脚 */}
      <FooterPro />

      {/* Toast通知 */}
      <ToastContainer
        position="top-right"
        autoClose={3000}
        hideProgressBar={false}
        newestOnTop
        closeOnClick
        rtl={false}
        pauseOnFocusLoss
        draggable
        pauseOnHover
        theme="dark"
        toastClassName="!glass-effect-dark !border !border-white/10 !rounded-xl !shadow-xl !backdrop-blur-xl"
        bodyClassName="text-sm md:text-base font-medium"
        progressClassName="!bg-gradient-to-r !from-primary-500 !to-primary-600"
      />
      
      {/* 订单列表模态框 */}
      {showOrderList && (
        <Suspense fallback={<OrderListSkeleton />}>
          <OrderList isOpen={showOrderList} onClose={() => setShowOrderList(false)} />
        </Suspense>
      )}
      
      {/* 地址管理模态框 */}
      {showAddressManager && (
        <Suspense fallback={<OrderListSkeleton />}>
          <AddressManager isOpen={showAddressManager} onClose={() => setShowAddressManager(false)} />
        </Suspense>
      )}
      
      {/* 帮助按钮 */}
      <HelpButton />
    </div>
  )
}

export default App
